package com.yesep.learn.utils;

import java.util.stream.IntStream;

public class TheadLocalTest {
    static ThreadLocal<TestContext> localVar = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        localVar.set(new TestContext("main", 10));
        System.out.println(" main start :" + localVar.get());
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                localVar.set(new TestContext("thread1", 30)); //设置线程1中本地变量的值
                IntStream.range(0, 30).forEach(i -> {
                    TestContext t = localVar.get();
                    t.setAge(t.getAge() - 1);
                    System.out.println(i + "..." + t);
                });
                localVar.remove();//清除本地内存中的本地变量
                System.out.println(" thread1 end :" + localVar.get());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                localVar.set(new TestContext("thread2", 50)); //设置线程2中本地变量的值
                IntStream.range(0, 50).forEach(i -> {
                    TestContext t = localVar.get();
                    t.setAge(t.getAge() + 1);
                    System.out.println(i + "..." + t);
                });
                localVar.remove();//清除本地内存中的本地变量
                System.out.println(" thread2 end :" + localVar.get());
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(2000l);
        System.out.println(" main end :" + localVar.get());
    }
}

class TestContext {
    private String name;

    private int age;

    public TestContext(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}